import 'dart:io';
import 'dart:ui';

import 'package:flutter_elf/base/base_page_state.dart';
/// CreateTime 2020/7/8 17:32
/// CreateUser chen 
/// ProjectName flutter_elf
///
import 'dart:isolate';
import 'package:flutter_elf/config/component_index.dart';
import 'package:m3u8_downloader/m3u8_downloader.dart';
import 'package:path_provider/path_provider.dart';
class M3u8DownloadPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return M3u8DownloadPageState();
  }
}

class M3u8DownloadPageState extends BasePageState<M3u8DownloadPage>{
  ReceivePort _port = ReceivePort();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    M3u8Downloader.initialize();
    _port.listen((dynamic data) {
      // 监听数据请求
      print(data);
    });
    _findSavePath();
  }

  //保存路径
  _findSavePath() async {
    final directory = Platform.isAndroid
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    String saveDir = directory.path + '/vPlayDownload';
    Directory root = Directory(saveDir);
    if (!root.existsSync()) {
      await root.create();
    }
    M3u8Downloader.config(debugMode: true, saveDir: saveDir);
  }
  static progressCallback(dynamic args) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port');
    args["status"] = 1;
    send.send(args);
  }
  static successCallback(dynamic args) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send({"status": 2, "url": args["url"]});
  }
  static errorCallback(dynamic args) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send({"status": 3, "url": args["url"]});
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBarCreator.create(context, '下载'),
      body: RaisedButton(
        onPressed: (){
          M3u8Downloader.download(
              url: "https://media001.geekbang.org/f433fd1ce5e84d27b1101f0dad72a126/de563bb4aba94b5f95f448b33be4dd9f-9aede6861be944d696fe365f3a33b7b4-sd.m3u8",
              progressCallback: progressCallback,
              successCallback: successCallback,
              errorCallback: errorCallback
          );
        },
        child: Text('下载'),
      ),
    );
  }
}